package org.sql.statement.builder;

import java.util.List;

import org.sql.statement.util.StatementUtil;

public class AbstractStatementBuilder implements Constants {

	protected static StringBuilder buildColumnsFragment(
			boolean isSelectAsterisk, List<String> list) {
		if (isSelectAsterisk || list.isEmpty())
			return new StringBuilder(STR_STAR);

		return new StringBuilder(buildFragment(list));
	}

	protected static String buildFragment(List<?> list) {
		final StringBuilder sb = new StringBuilder();

		for (Object str : list)
			sb.append(str).append(STR_COMMA_SPACE);

		return StatementUtil.getAllButLast(sb, STR_COMMA_SPACE.length());
	}

	protected static StringBuilder buildFromFragment(final List<String> list) {
		return new StringBuilder("FROM").append(CHAR_SPACE).append(
				buildTablesFragment(list));
	}

	protected static String buildMarksFragment(int size) {
		final StringBuilder sb = new StringBuilder();

		for (int i = 0; i < size; i++)
			sb.append("?").append(STR_COMMA_SPACE);

		return StatementUtil.getAllButLast(sb, STR_COMMA_SPACE.length());
	}

	protected static String buildMarksFragment(List<?> argumentsValues) {
		final StringBuilder sb = new StringBuilder();

		for (int i = 0; i < argumentsValues.size(); i++)
			sb.append("?").append(STR_COMMA_SPACE);

		return StatementUtil.getAllButLast(sb, STR_COMMA_SPACE.length());
	}

	protected static StringBuilder buildTablesFragment(final List<String> list) {
		if (list.isEmpty())
			StatementUtil.throwException("No table(s) set!", list.toString());

		return new StringBuilder(buildFragment(list));
	}

	protected static String buildWhereFragment(List<WhereClause> list) {
		final StringBuilder sb = new StringBuilder();

		if (!list.isEmpty())
			sb.append("WHERE").append(CHAR_SPACE);

		for (WhereClause whereArgument : list)
			sb.append(whereArgument.build());

		return sb.toString();
	}
}
